package api

import (
	"g_ansible/ansible/model"
	"github.com/gin-gonic/gin"
)

type V2HostApi struct {
}

func (p *V2HostApi) QueryHandler(c *gin.Context) {
	handler, err := v2hostService.Query()
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	} else {
		c.JSON(200, gin.H{"code": "200", "data": handler})
		return
	}
}

func (p *V2HostApi) AddHandler(c *gin.Context) {
	var inv model.Inventory
	if err := c.ShouldBindJSON(&inv); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	err := v2hostService.Add(inv)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	} else {
		c.JSON(200, gin.H{"code": "200", "data": "添加成功"})
	}
}

// Update 更新指定主机组中的主机信息
func (b *V2HostApi) UpdateHandler(c *gin.Context) {
	//groupName
	var inv model.Inventory
	if err := c.ShouldBindJSON(&inv); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	var groupName string
	var hostname string
	var hostvars model.HostVars
	for gn, g := range inv {
		for hn, hv := range g.HostVars {
			groupName = gn
			hostname = hn
			hostvars = hv

		}
	}
	err := v2hostService.Update(groupName, hostname, hostvars)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"code": "200", "data": "更新成功"})
}

func (b *V2HostApi) DeleteHandler(c *gin.Context) {
	// 获取要删除的主机信息
	var groupName, hostAlias string

	// 检查是否通过路径参数传递
	groupName = c.Param("group")
	hostAlias = c.Param("host")

	// 如果路径参数为空，则检查查询参数
	if groupName == "" || hostAlias == "" {
		groupName = c.Query("group")
		hostAlias = c.Query("host")
	}

	// 检查参数是否完整
	if groupName == "" || hostAlias == "" {
		c.JSON(400, gin.H{"error": "缺少必要的参数: group 和 host"})
		return
	}
	err := v2hostService.Delete(groupName, hostAlias)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"code": "200", "data": "删除成功"})
}
